module MyRestTestHelpers
  def check_json_response json
    @response.should be_success
    json = ActiveSupport::JSON.encode(json)
    ActiveSupport::JSON.decode(@response.body).should == ActiveSupport::JSON.decode(json)
  end

  def from_json obj
    ActiveSupport::JSON.decode(obj)
  end

  def to_json obj
    ActiveSupport::JSON.encode(obj)
  end

  module ReturnJsonMather
    class ReturnJson
      def initialize(expected)
        @expected = ActiveSupport::JSON.decode(ActiveSupport::JSON.encode(expected))
      end

      # target should be response
      def matches?(target)
        @target = ActiveSupport::JSON.decode(target.body)
        @target == @expected
      end

      def failure_message
        "expected <#{@expected}> to " +
        "the same as <#{@target}>"
      end

      def negative_failure_message
        "expected <#{@expected}> not to " +
        "be the same as <#{@target}>"
      end

      def to_s
        @expected.to_s
      end
    end

    # Actual matcher that is exposed.
    def return_json (expected = {})
      ReturnJson.new(expected)
    end
  end
end